#!/bin/sh
#desc:Local storage

# Copyright(c) 2011 OpenDomo Services SL. Licensed under GPL v3 or later

mkdir -p /media/

# Por precaución, reaplicamos permisos importantes
chown admin:admin /media
chown admin:admin /mnt/
chown admin:admin -R /usr/share/
ls -lah /var > /tmp/varlist.txt

/usr/bin/logger "Mounting drives"


# CD, VM, ODNetwork, RPi
DRIVEORDER="sr0 sda sda1 hda hda1 mmcblk0p1 mmcblk0p2"

start(){
  # Hack for ISO auto-mounting and misconfigured systems
  OPTIONS="rw,nosuid,uid=1000,gid=100,dmask=0027,fmask=0027,flush"
  for d in sr0 sda sdb sdc hda hdb hdc hdd; do
	  if test -e /dev/$d && ! test -e /mnt/$d; then
	  	mkdir /mnt/$d
	  	# Try to mount with options, otherwise without.
	  	mount /dev/$d /mnt/$d -o $OPTIONS || mount /dev/$d /mnt/$d 
	  fi
  done

  
  FSORDER="ext4 ext3 ext2 iso9660 vfat"
  for dev in $DRIVEORDER; do
	#for fs in $FSORDER; do
		#if ! test -d /mnt/$dev; then
		#	# Tener en cuenta los tipos particulares de FS
		#	if test "$fs" = "vfat"; then
		#		# Posiblemente se trate de un pendrive, ya que
		#		# no es ningún sistema nativo de Linux. Hay que
		#		# dar acceso a todos los usuarios, ya que el 
		#		# owner será root:root.
		#		op=" -o fmask=0111,dmask=0000,sync "
		#	else
		#		op=""
		#	fi
		#	mkdir -p /mnt/$dev
		#	if mount -t $fs /dev/$dev /mnt/$dev $op 2>/dev/null
			if test -d /mnt/$dev
			then
				/usr/bin/logger "Mounting $dev"
				echo -n "($dev)"
				logger "Device $dev detected"
				if test -e /mnt/$dev/opendomo.cfg; then
					/sbin/process_disk $dev
				else
					# Creamos el archivo de configuración y le asignamos permisos
					# para que pueda configurarse desde la interfaz
					touch /mnt/$dev/opendomo.cfg 2>/dev/null
					chown admin /mnt/$dev/opendomo.cfg 2>/dev/null
				fi
#				break;
			else 
				/usr/bin/logger "$dev not found"
		#		rm -fr /mnt/$dev
			fi
		#fi
	#done
  done
}


stop(){
	sync; sync
	for i in /mnt/*; do
		umount /dev/$i 2> /dev/null
		echo -n "($i)"
	done
	/bin/umount -a -r 2> /dev/null
	/sbin/swapoff -a 2> /dev/null
}

case $1 in 
  start)
	echo -n "Mounting drives..."
	start
  ;;
  stop)
	echo -n "Unmounting filesystems..."
	stop
  ;;
  reload|restart)
	echo -n "Re-checking drives..."
	start
  ;;
  *)
	echo "Usage: $0 {start|stop|restart|reload}"
	exit 1

esac
exit 0
